<template>
  <div class="cover" :style="{ width: coverWidth + 'px', height: coverWidth * scale + 'px' }">
    <el-image :src="coverFile as string" fit="scale-down" :width="cutWidth" v-if="coverFile">
      <template #error>
        <div class="iconfont icon-image-error"></div>
      </template>
      {{ 222222222 }}
    </el-image>
    <div class="mask" @click="selectImage">{{ coverImage ? '重新上传' : '上传' }}</div>
  </div>
  <ImageCoverCut ref="imageCoverCutRef" :cutWidth="cutWidth" :scale="scale"></ImageCoverCut>
</template>

<script setup lang="ts">
import ImageCoverCut from './ImageCoverCut.vue'
import { useRoute, useRouter } from 'vue-router'
import { ref, withDefaults } from 'vue'
import { asyncComputed } from '@vueuse/core'
import { useHomeStore } from '@/stores/home'

const route = useRoute()
const router = useRouter()
const homeStore = useHomeStore()

const props = withDefaults(
  defineProps<{
    coverImage: string | File
    coverWidth: number
    cutWidth: number
    scale: number
  }>(),
  {
    coverWidth: 100,
    cutWidth: 150,
    scale: 1
  }
)

const coverFile = asyncComputed(async () => {
  if (!props.coverImage) {
    return null
  }
  if (typeof props.coverImage == 'string') {
    return homeStore.sourcePath + props.coverImage
  } else if (props.coverImage instanceof File) {
    const base64 = await convertFileToBase64(props.coverImage)
    return base64
  }
})

const convertFileToBase64 = (base64: File) => {
  return new Promise((resolve, reject) => {
    let img = new FileReader()
    img.readAsDataURL(base64)
    img.onload = ({ target }) => {
      resolve(target?.result)
    }
  })
}

const imageCoverCutRef = ref()
const selectImage = () => {
  imageCoverCutRef.value.show()
}
</script>

<style lang="less" scoped>
.cover {
  background-color: #f0f0f0;
  position: relative;
  .mask {
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 0;
    height: 30px;
    background: rgba(0, 0, 0, 0.7);
    opacity: 0.8;
    z-index: 1;
    color: #fff;
    text-align: center;
    cursor: pointer;
  }
}
</style>
